import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//三数之和
class Solution2 {
    public List<List<Integer>> threeSum(int[] nums) {
        Arrays.sort(nums);

        List<List<Integer>> whole = new ArrayList();

        for (int i = 0; i < nums.length; ) {
            if (nums[i] > 0) {
                break;
            }
            int left = i + 1;
            int right = nums.length - 1;

            while (left < right) {
                int tag = -nums[i];
                int tmp = nums[right] + nums[left];
                if (tmp > tag) {
                    right--;
                } else if (tmp < tag) {
                    left++;
                } else {
                    whole.add(new ArrayList<Integer>(Arrays.asList(nums[i], nums[left], nums[right])));

                    left++;
                    right--;
                    while (left < right && nums[left - 1] == nums[left]) {
                        left++;
                    }
                    while (left < right && nums[right + 1] == nums[right]) {
                        right--;
                    }

                }
            }
            i++;
            while (i < nums.length && nums[i - 1] == nums[i]) {
                i++;
            }

        }
        return whole;
    }
}